package com.jcx.ldzj.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcx.ldzj.dao.DeptUserMapper;
import com.jcx.ldzj.dto.UserInfoDTO;
import com.jcx.ldzj.emun.MyCode;
import com.jcx.ldzj.entity.DepartmentInfo;
import com.jcx.ldzj.entity.DeptUser;
import com.jcx.ldzj.service.IDepartmentInfoService;
import com.jcx.ldzj.service.IDeptUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Ð¡Ìì
 * @since 2021-01-20
 */
@Slf4j
@Service
@Transactional
public class DeptUserServiceImpl extends ServiceImpl<DeptUserMapper, DeptUser> implements IDeptUserService {


    @Autowired
    private IDepartmentInfoService iDepartmentInfoService;

    public UserInfoDTO saveUserToDept(UserInfoDTO userInfo){
        List<DeptUser> list=userInfo.getDepIds();
        String deptId="";
        String deptName="";
        //清空之前的部门与用户的对象
        this.deleteByuserId(userInfo.getId());
        for (int i = 0;list!=null&& i < list.size(); i++) {
            try {
                DepartmentInfo dept = iDepartmentInfoService.getById(list.get(i));
                deptId+=dept.getId()+",";
                deptName+=dept.getDepName()+",";
                DeptUser deptUser= new DeptUser();
                deptUser.setDepId(dept.getId());
                deptUser.setDepName(dept.getDepName());
                deptUser.setUserId(userInfo.getId());
                deptUser.setUserName(userInfo.getUserName());
                this.save(deptUser);
            }catch (Exception e){
                log.error(MyCode.新增部门与用户之关系失败.getMsg()+"失败的部门id为：{}失败的用户id为：{}错误原因：{}",list.get(i),userInfo.getId(),e);
            }
        }
        if(list!=null&&list.size()>0){
            userInfo.setDepId(deptId.substring(0,deptId.length()-1));
            userInfo.setDepName(deptName.substring(0,deptName.length()-1));
        }
        return userInfo;
    }
    @Override
    public boolean deleteByuserId(String userId) {
        return this.baseMapper.deleteByuserId(userId);
    }

    @Override
    public boolean deleteBydeptId(String deptId) {
        return this.baseMapper.deleteBydeptId(deptId);
    }

    @Override
    public List<DeptUser> getListByAll(DeptUser deptUser) {
        return this.baseMapper.getListByAll(deptUser);
    }


    @Override
    public int getDeptUserCount(DeptUser deptUser) {
        return this.baseMapper.getDeptUserCount(deptUser);
    }
}
